<?php

namespace App\Controller\LazyCommon;

use App\Base\BaseController;
use App\Model\LazyCommon\UserModel;
use App\Entity\WechatCode;
use App\Model\LazyCommon\WechatCodeModel;
use App\Model\LazyCommon\WechatModel;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * @route("/wechatCode")
 */
class WechatCodeController extends BaseController
{

    /**
     * @route("/bindPhone",name="WechatBindPhone")
     */
    public function index(Request $request)
    {
        if ($request->getMethod() == "POST") {

            if(!$id = $this->getParamRequired("id")){die;}
            if(!$phone = $this->getParamRequired("phone")){
                $message = "手机号输入有误";
                return $this->redirectToRoute("WechatBindPhone",array("id"    => $id,"message"    => $message));
            }
            $WechatCodeModel = new WechatCodeModel($this->getDoctrine());
            $WechatCode = $WechatCodeModel->getByPhone($phone);
            if ($WechatCode) {
                $message = "手机号已占用，请在公众号留言留言【手机号占用，手机号：XXXXXXXXX】";
                return $this->redirectToRoute("WechatBindPhone",array("id"    => $id,"message"    => $message));
            }
            //todo 应该记录更换手机号的频率，对于频繁更换手机号的做出限制
            if (!$WechatCode = $WechatCodeModel->getByOpenid($id)) {
                $WechatCode = new WechatCode();
            }

            $WechatCode->setOpenid($id)
                ->setPhone($phone)
                ->setCode(0)
                ->setAddtime(0);
            $this->myEm()->persist($WechatCode);
            $this->myEm()->flush();
            $message = "绑定成功";
            return $this->redirectToRoute("WechatBindPhone",array("id"    => $id,"message"    => $message));

        } else {
            if(!$id = $this->getParamRequired("id")){die;}
            if(!$message = $this->getParamRequired("message")){$message = "";}
            $data = array(
                "id"    => $id,
                "message"    => $message,
            );
            return $this->render('App:WechatCode:bind.html.twig',$data);
        }
    }

}